package com.ophiux.cs.application.consultBase.impl;

import com.ophiux.cs.application.consultBase.dto.GetDeptRequest;
import com.ophiux.cs.application.consultBase.dto.GetDeptResponse;
import com.ophiux.cs.application.consultBase.service.IGetDeptAppService;
import com.ophiux.cs.application.core.AppResultCode;
import com.ophiux.cs.application.core.ResponsePage;
import com.ophiux.cs.application.core.Result;
import com.ophiux.cs.application.core.ResultEnum;
import com.ophiux.cs.domain.consultBase.model.valueobj.DeptParentResult;
import com.ophiux.cs.domain.consultBase.model.valueobj.DeptQueryObj;
import com.ophiux.cs.domain.consultBase.model.valueobj.DeptResult;
import com.ophiux.cs.domain.consultBase.repositories.IDeptRepository;
import com.ophiux.utils.common.ShiftUtils;
import com.ophiux.utils.exception.OphiuxRepositoryException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class GetDeptAppService implements IGetDeptAppService {

    @Autowired
    IDeptRepository deptRepositories;


    @Override
    public Result<ResponsePage<GetDeptResponse>> getDept(GetDeptRequest dto) {
        ResponsePage<GetDeptResponse> resp=new ResponsePage<GetDeptResponse>();
        //验证参数是否允许为空
        if(!dto.isParamValid()) {
            return Result.fail(ResultEnum.requestParamFail.getCode(), ResultEnum.requestParamFail.getMsg());
        }
        try {
            DeptQueryObj dept = null;
            dept = (DeptQueryObj) ShiftUtils.objToNewObj(dto, DeptQueryObj.class);
            try {
                //查找所有一级科室
                List<DeptParentResult> deptList=deptRepositories.getParentDept(dept);
                for (int i=0;i<deptList.size();i++){
                    DeptParentResult dspr=deptList.get(i);
                    //查询二级科室
                    List<DeptResult> dsList=deptRepositories.getDeptByParentId(dspr.getDEPT_ID());
                    dspr.setDEPT_CHILDS(dsList);
                }
                //查找所有一级科室
               int count=deptRepositories.getParentDeptCount(dept);
                List<GetDeptResponse> returnList = ShiftUtils.objToNewObjList(deptList, GetDeptResponse.class);
                resp.initData(returnList,count,dept);
            } catch (OphiuxRepositoryException e) {
                e.printStackTrace();
                return Result.fail(ResultEnum.requestException.getCode(), e.getExceptionMessage());
            }
        } catch (Exception e) {
            log.info("【getDept】接口异常：",e);
            e.printStackTrace();
            return Result.fail(AppResultCode.EXCEPTION, "程序异常");
        }
        return Result.success(resp, "查询科室成功");
    }
}
